package cn.xawl.interview.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lh
 * @date 2020/08/25 15:53:35
 *
 * 公平锁/非公平锁/可重入锁/递归锁/自旋锁
 *
 * 可重入锁：
 * 12	线程开始发送短信
 * ##########
 * 发送成功！
 * 12	线程开始发送邮件
 * ##########
 * 发送成功！
 * 13	线程开始发送短信
 * ##########
 * 发送成功！
 * 13	线程开始发送邮件
 * ##########
 * 发送成功！
 *
 **/
public class ReentrantLockDemo {

    public static void main(String[] args) {

        Phone phone = new Phone();
        new Thread(() -> {
            phone.sendSms();
        }, "t1").start();

        new Thread(() -> {
            phone.sendSms();
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(12);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread t3 = new Thread(phone, "t3");
        Thread t4 = new Thread(phone, "t4");

        t3.start();
        t4.start();
    }

}


class Phone implements Runnable{
    public synchronized void sendSms() {
        System.out.println(Thread.currentThread().getId() + "\t线程开始发送短信");
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i == 9) {

                System.out.println("#");
            } else {
                System.out.print("#");
            }
        }
        System.out.println("发送成功！");
        sendEmail();
    }
    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getId() + "\t线程开始发送邮件");
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i == 9) {

                System.out.println("#");
            } else {

                System.out.print("#");
            }
        }
        System.out.println("发送成功！");

    }

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        Thread.yield();
        get();
    }

    public void get() {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getId() + "\tget方法执行");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        set();
    }

    public void set() {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getId() + "\tset方法执行");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
